package com.lkd.http.controller;

import com.github.wxpay.plus.WXConfig;
import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.common.VMSystem;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.service.OrderService;
import com.lkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayTemplate wxPayTemplate;

    /**
     * 微信支付
     *
     * @param payVO
     * @return
     */
    @PostMapping("/weixinPay")
    public Map<String, String> weixinPay(@RequestBody PayVO payVO) {
        OrderEntity order = orderService.createOrder(payVO);
        WxPayParam wxPayParam = new WxPayParam();
        wxPayParam.setBody(order.getSkuName());
        wxPayParam.setOutTradeNo(order.getOrderNo());
        wxPayParam.setTotalFee(order.getAmount());
        wxPayParam.setOpenid(order.getOpenId());
        return wxPayTemplate.requestPay(wxPayParam);
    }


    /**
     * 微信支付回调接口
     *
     * @param request
     * @return
     */
    @RequestMapping("/payNotify")
    @ResponseBody
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        log.info("支付回调");
        try {
            Map<String, String> result = wxPayTemplate.validPay(request.getInputStream());
            if ("SUCCESS".equals(result.get("code"))) {  //返回码成功
                String orderSn = result.get("order_sn");//获取订单号
                log.info("支付成功，修改订单状态和支付状态，订单号：{}", orderSn);
                OrderEntity orderEntity = orderService.getByOrderNo(orderSn);
                if (orderEntity != null) {
                    orderEntity.setStatus(VMSystem.ORDER_STATUS_PAYED);
                    orderEntity.setPayStatus(VMSystem.PAY_STATUS_PAYED);
                    orderService.updateById(orderEntity);
                    //出货方法
//                    OrderEntity orderEntity = new OrderEntity();
//                    orderEntity.setOrderNo("01000001525296385226100");
//                    orderEntity.setSkuId(2L);
//                    orderEntity.setInnerCode("01000001");
                    orderService.vendOut(orderEntity.getOrderNo(), orderEntity.getSkuId(), orderEntity.getInnerCode());
                }
            }
            //给微信支付一个成功的响应
            response.setContentType("text/xml");
            response.getWriter().write(WXConfig.RESULT);
        } catch (Exception e) {
            log.error("支付回调处理失败", e);
        }
    }

}
